package com.jsoft.jsofted.sys.service.impl;

import com.jsoft.jsofted.sys.entity.PostEntity;
import com.jsoft.jsofted.sys.mapper.PostMapper;
import com.jsoft.jsofted.framework.mybatis.CocQueryWrapper;
import com.jsoft.jsofted.framework.service.impl.CocServiceImpl;
import com.jsoft.jsofted.sys.service.PostService;
import com.jsoft.jsofted.sys.vo.PostBean;
import com.jsoft.jsofted.sys.vo.PostTreeMaker;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class PostServiceImpl extends CocServiceImpl<PostMapper, PostEntity> implements PostService {

    @Override
    public List<PostBean> queryTree(Map queryParams) {
        List list = list(parseQueryWrapper(queryParams));
        return PostTreeMaker.make(list);
    }

    protected CocQueryWrapper parseQueryWrapper(Map queryParams) {
        if (queryParams == null) {
            queryParams = new LinkedHashMap();
        }

        CocQueryWrapper queryWrapper = new CocQueryWrapper();
        this._parseSortParams(queryWrapper, queryParams);
        this._parseKeywordsParams(queryWrapper, queryParams);
        this._parseOrgParams(queryWrapper, queryParams);

        return queryWrapper;
    }

    /**
     * 解析【条件参数】中的【机构参数】
     * 即查询指定的机构设置了哪些职位（岗位）
     */
    private void _parseOrgParams(CocQueryWrapper queryWrapper, Map queryParams) {
        String orgId = (String) queryParams.get("orgId");
        if (StringUtils.hasText(orgId)) {
            queryWrapper.subSelect("id", "in",
                    "(select post_id from sys_post_org where org_id = {0})", orgId);
        }
    }

    private void _parseSortParams(CocQueryWrapper queryWrapper, Map queryParams) {
        queryWrapper.orderByDesc("sort_value", "create_time");
    }

    /**
     * 解析【条件参数】中的【关键字参数】
     */
    private void _parseKeywordsParams(CocQueryWrapper queryWrapper, Map condParams) {
        String keywords = (String) condParams.get("keywords");
        if (StringUtils.hasText(keywords)) {
            queryWrapper.like("name", keywords);
        }
    }

}
